package com.hqq.concurrency.semaphone;

/**
 * Semaphore
 * Created by heqianqian on 2017/7/30.
 */
public class Semaphore implements Lock {

    private final int licenses;

    private int counter;

    public Semaphore(int counter) {
        this.counter = counter;
        this.licenses = counter;
    }

    public int getNumLicenses() {
        return this.licenses;
    }

    public int getAvailableLicenses() {
        return counter;
    }

    @Override
    public synchronized void acquire() throws InterruptedException {
        while (counter == 0) {
            wait();
        }
        counter = counter - 1;
    }

    @Override
    public synchronized void release(){
        if (counter < licenses) {
            counter = counter + 1;
            notify();
        }
    }
}
